
package com.way.filemanager.util;

import hwdroid.dialog.AlertDialog;
import hwdroid.dialog.DialogInterface;
import hwdroid.dialog.DialogInterface.OnClickListener;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.way.filemanager.R;
import com.way.filemanager.ui.dialogs.CustomProgressDialog;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.Deflater;

public class ZipDialog {
    private static final String TAG = "ZipDialog";
    Context mActivity;

    final List<File> FileFullPath;
    String FileDir;
    int MAX = 100;
    int MAX_SHOW = 90;
    Thread mThread;
    LocalHandler mLocalHandler;
    boolean bIsForceStop = false;
    CustomProgressDialog mCustomProgressDialog;
    long systemtime = System.currentTimeMillis();
    long unzip_size = 0;
    long file_size = 1;

    public ZipDialog(Context m, List<File> filename, String Dir) {
        bufSize = 1024 * 4;
        buf = new byte[bufSize];

        mActivity = m;
        FileFullPath = filename;
        FileDir = Dir;
        Log.v(TAG, "ZipDialog filename:" + filename);
        mCustomProgressDialog = CustomProgressDialog.create(mActivity, mActivity.getResources()
                .getString(R.string.dialog_title_do_Zip));

        mCustomProgressDialog.setButton(AlertDialog.BUTTON_NEGATIVE, mActivity.getResources()
                .getString(R.string.cancel), new OnClickListener() {
            public void onClick(hwdroid.dialog.DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                bIsForceStop = true;
                Log.v(TAG, "ZipDialog canceling");
            }
        });
        mCustomProgressDialog.setProgress(MAX);
        CommonFunc.TA_Click(CommonFunc.OnClick_Zip);
        Log.v(TAG, "ZipDialog");
    }

    final int Unzip_finish_id = 1;
    final int Unzip_ShowProgress_id = 2;
    final int Unzip_NotSpace_id = 3;
    final String Unzip_ShowProgress_key_precent = "progress_precent";
    final String Unzip_ShowProgress_key_filename = "progress_filename";
    EditText mTextView;
    public void show() {
        Log.v(TAG, "ZipDialog show:" + FileFullPath);
        mLocalHandler = new LocalHandler();
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                boolean ret = false;
                if(mTextView != null)
                {
                    String name = mTextView.getText().toString();
                    if((name!=null)&&(name.length()>0))
                    {
                        FileDir = FileDir+File.separator+ name + ".zip";
                        File Dest = new File(FileDir);
                        if(!(Dest.exists()&&Dest.isFile()))
                        {
                            ret = true;
                        }
                    }
                }
                if(!ret)
                {
                    Toast.makeText(mActivity, R.string.ali_ZipError, Toast.LENGTH_SHORT)
                    .show();
                    return ;
                }
                mCustomProgressDialog.show();
                mThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        long BaseNum = 0;
                        for(File file:FileFullPath)
                        {
                            BaseNum = CommonFunc.listDirFileNum(file, BaseNum);
                        }
                        file_size = BaseNum;
                        // TODO Auto-generated method stub
                        doZip(FileFullPath, FileDir);
                        mLocalHandler.removeMessages(Unzip_ShowProgress_id);
                        mLocalHandler.sendEmptyMessage(Unzip_finish_id);
                    }

                });
                mThread.start();
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        });

        builder.setTitle(R.string.actions_title_Zip);
        LayoutInflater factory = LayoutInflater.from(mActivity);
        final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry_mkdir, null);
        mTextView = (EditText) textEntryView.findViewById(R.id.mkdir_edit);
        String filename = FileFullPath.get(0).getName();
        if(filename!=null)
        {
            int index = filename.indexOf(".");
            if(index>0)
                filename = filename.substring(0,index);
            mTextView.setText(filename);
        }
        mTextView.setOnFocusChangeListener(new OnFocusChangeListener(){
            @Override
            public void onFocusChange(View arg0, boolean arg1) {
                // TODO Auto-generated method stub
                // ((EditText)arg0).setText(null);
                arg0.setOnFocusChangeListener(null);
            }

        });
        AlertDialog dd = builder.create();
        dd.setView(textEntryView);
        dd.show();

    }

    /**
     *
     * 
     * @param srcFile
     * @param destFile
     */
    private ZipFile zipFile;
    private ZipOutputStream zipOut;
    private int bufSize; // size of bytes
    private byte[] buf;

    public void doZip(List<File> srcFile, String destFile) {

        try {
            this.zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(
                    destFile)));
            zipOut.setComment("comment");
            zipOut.setEncoding("GBK");
            zipOut.setMethod(ZipOutputStream.DEFLATED);

            zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);
            for (File zipFile : srcFile) {
                //File zipFile = new File(msrc);
                handleFile(zipFile, this.zipOut, "");
            }
            this.zipOut.close();
        } catch (IOException ioe) {
            File tmpFile = new File(destFile);
            if(tmpFile.exists())
                tmpFile.delete();
            Message msg = mLocalHandler.obtainMessage(Unzip_NotSpace_id);
            mLocalHandler.sendMessage(msg);
            ioe.printStackTrace();
        }
    }

    /**
     *
     * 
     * @param zipFile
     * @param zipOut
     * @param dirName
     * @throws IOException
     */
    private void handleFile(File zipFile, ZipOutputStream zipOut, String dirName)
            throws IOException {
        if(bIsForceStop)
            return;
        if (zipFile.isDirectory()) {
            File[] files = zipFile.listFiles();

            if (files.length == 0) {
                this.zipOut
                        .putNextEntry(new ZipEntry(dirName + zipFile.getName() + File.separator));
                this.zipOut.closeEntry();
            } else {
                for (File file : files) {
                    handleFile(file, zipOut, dirName + zipFile.getName() + File.separator);
                }
            }
        }
        else {
            FileInputStream fileIn = new FileInputStream(zipFile);
            this.zipOut.putNextEntry(new ZipEntry(dirName + zipFile.getName()));
            int length = 0;
            while ((length = fileIn.read(this.buf)) > 0) {
                this.zipOut.write(this.buf, 0, length);
                if(bIsForceStop)
                    break;
            }
            this.zipOut.closeEntry();
            unzip_size++;
            if ((System.currentTimeMillis() - systemtime) > 100) {
                int precent;
                precent = (int) (unzip_size * MAX / file_size);
                Message msg = mLocalHandler.obtainMessage(Unzip_ShowProgress_id);
                Bundle msg_data = new Bundle();
                msg_data.putInt(Unzip_ShowProgress_key_precent, precent);
                msg_data.putString(Unzip_ShowProgress_key_filename, zipFile.getName());
                msg.setData(msg_data);
                mLocalHandler.removeMessages(Unzip_ShowProgress_id);
                mLocalHandler.sendMessage(msg);
                systemtime = System.currentTimeMillis();
            }
        }

    }

    @SuppressLint("HandlerLeak")
    public class LocalHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            Log.v(TAG, "ZipDialog msg.what:" + msg.what);
            switch (msg.what) {
                case Unzip_finish_id:
                    // filenameTxt.setText("Finished!!!");
                    mLocalHandler.removeMessages(Unzip_finish_id);
                    mCustomProgressDialog.dismiss();
                    break;
                case Unzip_ShowProgress_id:
                    mLocalHandler.removeMessages(Unzip_ShowProgress_id);
                    Bundle data = msg.getData();
                    int precent = data.getInt(Unzip_ShowProgress_key_precent);
                    if (precent > MAX_SHOW)
                        precent = MAX_SHOW;

                    // String precent_max = String.valueOf(precent) + "/" + MAX;
                    String filename = data.getString(Unzip_ShowProgress_key_filename);
                    mCustomProgressDialog.setMessage(filename);
                    mCustomProgressDialog.setProgress(precent);
                    break;
                case Unzip_NotSpace_id:
                    mLocalHandler.removeMessages(Unzip_NotSpace_id);
                    mCustomProgressDialog.dismiss();
                    Toast.makeText(mActivity, R.string.ali_NotEnoughSpace, Toast.LENGTH_LONG).show();
                    break;

                default:
                    break;
            }
        }
    }
}
